package com.phpxiu.app.api.callback;


import com.phpxiu.app.config.Constants;
import com.phpxiu.app.utils.KKYUtil;
import com.tencent.TIMConversation;
import com.tencent.TIMConversationType;
import com.tencent.TIMCustomElem;
import com.tencent.TIMElem;
import com.tencent.TIMElemType;
import com.tencent.TIMManager;
import com.tencent.TIMMessage;
import com.tencent.TIMMessageListener;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Observable;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @file
 * @brief 会话消息数量管理器,单例模式
 * @author 吴金洲
 * @note 会话消息数量管理器，被各显示消息数量的界面观察。
 *
 */
public class MsgCountManager extends Observable implements TIMMessageListener {
    public final static String TAG="MsgCountManager";
    private volatile static MsgCountManager instance;
    private AtomicLong msgCount=new AtomicLong(0L);//消息数量

    private MsgCountManager(){

    }

    public static MsgCountManager getInstance(){
        if (instance == null) {
            synchronized (MsgCountManager.class) {
                if (instance == null) {
                    instance = new MsgCountManager();
                }
            }
        }
        return instance;
    }

    /**
     * 初始化所有C2C会话未读信息个数
     */
    public void refreshMsgCount(){
        long tempCount=0;
        //获取会话个数
        long count = TIMManager.getInstance().getConversationCount();
        //遍历会话列表
        for(long i = 0; i < count; ++i) {
            //根据索引获取会话
            TIMConversation conversation = TIMManager.getInstance().getConversationByIndex(i);
            if (conversation.getType() == TIMConversationType.C2C) {
                KKYUtil.log(TAG + ":" + conversation.getPeer() + "==" + conversation.getUnreadMessageNum());
                if(!"live_admin".equals(conversation.getPeer())){
                    tempCount=tempCount+(int)conversation.getUnreadMessageNum();
                }
            }
        }
        msgCount.set(tempCount);
        setChanged();
        notifyObservers(msgCount.get());
        //通知观察者，有变动
    }

    /**
     * 消息接收监听，用于更新未读私信数量
     * @param timMessages
     * @return
     */
    @Override
    public boolean onNewMessages(List<TIMMessage> timMessages) {
        for (TIMMessage message : timMessages) {
            if (message.getConversation().getType() == TIMConversationType.C2C) {
                if (!Constants.SERVER_ADMIN_ID.equals(message.getConversation().getPeer())) {
                    boolean isIncrement=true;//是否消息数增加，连麦消息忽略
                    for (int j = 0; j < message.getElementCount(); j++) {
                        if (message.getElement(j) == null) {
                            continue;
                        }
                        TIMElem elem = message.getElement(j);
                        TIMElemType type = elem.getType();
                        if (type == TIMElemType.Custom) {//自定义消息，处理连麦消息
                            try {
                                String customText = new String(((TIMCustomElem) elem).getData(), "UTF-8");
                                JSONTokener jsonParser = new JSONTokener(customText);
                                // 此时还未读取任何json文本，直接读取就是一个JSONObject对象。
                                // 如果此时的读取位置在"name" : 了，那么nextValue就是"yuanzhifei89"（String）
                                JSONObject json = (JSONObject) jsonParser.nextValue();
                                int action = json.getInt(Constants.CMD_KEY);
                                KKYUtil.log(TAG + "自定义消息协议：" + action);
                                if((action>2059&&action<2067)||action== Constants.AVIMCMD_MUlTI_JOIN){//连麦段消息协议
                                    isIncrement=false;
                                    break;
                                }
                            }catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            } catch (JSONException ex) {
                                // 异常处理代码
                                ex.printStackTrace();
                            }
                        }
                    }
                    if(isIncrement){
                        msgCount.incrementAndGet();
                    }
                    //通知观察者，有变动
                    setChanged();
                    notifyObservers(msgCount.get());
                } else {
                    message.getConversation().setReadMessage(message);
                }
            }
        }
        return false;
    }

}
